package com.compass.web;

import com.compass.RedisLock;
import com.compass.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class WebController {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebController.class);
    @Value("${redis.key.repertory}")
    String repertory;

    @Autowired
    RedisTemplate<String,Integer> redisTemplate;

    @RequestMapping("/hi")
    public String hi(String name, HttpServletRequest httpServletRequest){
        SpringUtils.getBean("redisTemplate");
        int port = httpServletRequest.getServerPort();
        return "Hi "+name+",I am from "+port;
    }


    /**
     * 卖出商品
     * @return
     */
    @RequestMapping("sell")
    public String sellItem(String itemName,int num){
        RedisLock redisLock = new RedisLock(redisTemplate,itemName);
        try {
            redisLock.lock();
            Integer integer = Integer.parseInt(redisTemplate.opsForHash().get(repertory,itemName).toString());
            LOGGER.debug("item:{},sell:{},have:{}",itemName,num,integer);
            if(integer != null && integer >= num){
                redisTemplate.opsForHash().increment(repertory,itemName, 0-num);
            }else{
                redisTemplate.opsForHash().increment(repertory,itemName, num);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            redisLock.unlock();
        }

        return "sell ok";
    }

    /**
     *
     * @param itemName
     * @param num
     * @return
     */
    @RequestMapping("buy")
    public String addItem(String itemName,String num){
        try {
            redisTemplate.opsForHash().put(repertory,itemName,num);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "add ok";
    }

}
